﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace iSmartCreatorApp
{
    /// <summary>
    /// Interaction logic for DocumentTitleWindow.xaml
    /// </summary>
    public partial class DocumentTitleWindow : Window
    {
        public DocumentTitleWindow()
        {
            InitializeComponent();
            TxtBxDocTitle.Focus();
        }

        private void BtnChange_Click(object sender, RoutedEventArgs e)
        {
            NewDocument.pageTitle = TxtBxDocTitle.Text;
            ChangeTitle(MainWindow.currentRTBHtml);
            this.Close();
        }

        private void ChangeTitle(RichTextBox rtb)
        {
            Paragraph paragraph = new Paragraph();
            FlowDocument flow = new FlowDocument();

            var str = new TextRange(rtb.Document.ContentStart, rtb.Document.ContentEnd).Text;
            string[] arr = str.Split('\n');

            for (int i = 0; i < arr.Length; i++)
            {
                if (arr[i].StartsWith("<title>"))
                {
                    arr[i] = "<title>" + NewDocument.pageTitle + "</title>";
                    break;
                }
            }

            foreach (var s in arr)
            {
                if (s == "</html>")
                {
                    paragraph.Inlines.Add(s + "\n");
                    break;
                }
                paragraph.Inlines.Add(s + "\n");
            }
            flow.Blocks.Add(paragraph);

            rtb.Document = flow;

            MainWindow.dictionary["$title"] = NewDocument.pageTitle;
        }
    }
}
